package com.hippo.core.vm

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hippo.core.core.UserManger
import com.hippo.core.core.ext.toMd5
import com.hippo.core.dto.LoginDto
import com.hippo.core.respository.ApiRepository
import com.hippo.core.state.LoginState
import com.hippo.core.tuya.TuYaManager
import com.hippo.core.utils.UiHandler.showToast
import kotlinx.coroutines.launch

class LoginVM : ViewModel() {

    var uiState by mutableStateOf(LoginState())



    fun dismissLoading(){
        uiState = uiState.copy(isLoading = false)
    }

    fun updateEmail(email:String){
        uiState = uiState.copy(userEmail = email)
    }

    fun updatePassword(password:String){
        uiState = uiState.copy(password = password)
    }


    fun login(onSuccess:()->Unit){
        viewModelScope.launch {
            uiState = uiState.copy(isLoading = true)

            viewModelScope.launch {
                ApiRepository.login(LoginDto(
                    userEmail = uiState.userEmail,
                    password = uiState.password?.toMd5()
                ))
                    .onFailure {
                        showToast(it.msg?:"")
                        dismissLoading()
                    }
                    .onSuccess { userInfo ->

                        userInfo?.let{
                            TuYaManager.loginOrRegisterWithUid(
                                it.countryCode.orEmpty(),
                                it.userNo.toString(),
                                it.tuYaPwd.orEmpty(),
                                {
                                    userInfo.password = uiState.password
                                    UserManger.saveUserInfo(userInfo)
                                    dismissLoading()
                                    onSuccess()
                                },
                                {code, error ->
                                    showToast(error)
                                    dismissLoading()
                                }
                            )
                        }
                    }
            }

        }
    }


}